package com.suep.data_analysis.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.suep.data_analysis.dto.ArmamentDto;
import com.suep.data_analysis.mapper.ArmamentMapper;
import com.suep.data_analysis.model.Armament;
import com.suep.data_analysis.repository.ArmamentRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class ArmamentService {
    private final ArmamentRepository armamentRepository;
    private final ArmamentMapper armamentMapper;

    /**
     * 根据音擎ID查询详情
     */
    public ArmamentDto getArmamentById(String armamentId) {
        Objects.requireNonNull(armamentId, "音擎ID不能为null");

        // 构建查询条件
        Wrapper<Armament> query = Wrappers.<Armament>lambdaQuery()
                .eq(Armament::getArmamentId, armamentId);

        // 查询音擎信息
        Armament armament = armamentRepository.selectArmament(query).stream()
                .findFirst()
                .orElse(null);

        // 转换为DTO
        return armamentMapper.toArmamentDto(armament);
    }

    /**
     * 查询所有音擎（用于列表展示）
     */
    public List<ArmamentDto> getAllArmaments() {
        List<Armament> armaments = armamentRepository.selectAllArmament();
        return armaments.stream()
                .map(armamentMapper::toArmamentDto)
                .collect(Collectors.toList());
    }

    /**
     * 根据关键词搜索音擎（支持名称、类别、效果搜索）
     */
    public List<ArmamentDto> searchArmaments(String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return getAllArmaments(); // 空关键词返回全部
        }

        // 构建多字段搜索条件
        Wrapper<Armament> query = Wrappers.<Armament>lambdaQuery()
                .like(Armament::getArmamentName, keyword)
                .or()
                .like(Armament::getArmamentType, keyword)
                .or()
                .like(Armament::getEffectDescription, keyword);

        // 执行查询并转换为DTO
        List<Armament> armaments = armamentRepository.selectArmament(query);
        return armaments.stream()
                .map(armamentMapper::toArmamentDto)
                .collect(Collectors.toList());
    }
}